package cn.birdbaby.plugins.sync.fieldsyncer;

import cn.birdbaby.codegen.processor.creator.IgnoreCreator;
import cn.birdbaby.codegen.processor.updater.IgnoreUpdater;
import cn.birdbaby.plugins.annotator.fieldannotator.schema.BBAddSchemaAction;
import cn.birdbaby.plugins.sync.AbstractSyncer;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.PsiAnnotation;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiField;
import com.intellij.psi.util.PsiTreeUtil;

import java.util.Collection;
import java.util.List;

/**
 * @author llorando 13/8/24 11:14 am
 * 输入：当前处理的entity psiClass
 */
public abstract class AbstractFieldSyncer extends AbstractSyncer {

    @Override
    public String getElementName(PsiElement element) {
        return ((PsiField) element).getName();
    }

    public void sync(PsiClass psiClass) {
        PsiField[] fields = psiClass.getFields();
        PsiClass destination = findClass(psiClass);
        if(destination!=null) {
            List<PsiElement> filterPsiField = filterPsiElement(List.of(psiClass.getFields()), List.of(destination.getFields()));
            addPsiElement(destination, filterPsiField);
        }
    }

    //目前考虑的是entity字段比request类多的情况，如果request类存在entity没有的字段，如何处理？
    //不处理, 项目中多出来的字段大部分是为了适配前端加的，是必要的

    public abstract String getSuffix();

    //被Ignore注解标记的字段跳过
    public boolean skip(PsiElement psiField) {
        Collection<PsiAnnotation> psiAnnotations = PsiTreeUtil.findChildrenOfAnyType(psiField, PsiAnnotation.class);
        if (psiAnnotations.isEmpty()) return false;

        for (PsiAnnotation psiAnnotation : psiAnnotations) {
            String name = psiAnnotation.getNameReferenceElement().getReferenceName();
            if (IgnoreCreator.class.getSimpleName().equals(name) || IgnoreUpdater.class.getSimpleName().equals(name)) {
                return true;
            }
        }
        return false;
    }
}
